package com.taptech.doufu.presenter.novel
import android.app.Activity
import android.content.Intent
import android.widget.Toast
import com.taptech.doufu.app.WeMediaApplication
import com.taptech.doufu.bean.ShareBeansInfo
import com.taptech.doufu.constant.Constant
import com.taptech.doufu.model.novel.NovelDetailsModel
import com.taptech.doufu.model.novel.bean.NovelAttentionBean
import com.taptech.doufu.model.novel.bean.NovelCommentBean
import com.taptech.doufu.model.novel.bean.NovelDetailBean
import com.taptech.doufu.net.retrofit.api.BaseSubscriber
import com.taptech.doufu.presenter.BasePresenter
import com.taptech.doufu.services.personalcenter.AccountService
import com.taptech.doufu.ui.activity.base.DiaobaoBaseActivity
import com.taptech.doufu.util.GsonUtil
import com.taptech.doufu.util.SoftKeyboardUtil
import com.taptech.doufu.util.StringUtil
import com.taptech.doufu.util.sp.DiaoBaoSharedPreferences
import com.taptech.doufu.weex.http.TFHttpUtil

class StoryDetailsPresenter(context:Activity, view:IStoryDetailsView, intent:Intent) : BasePresenter<IStoryDetailsView>(context,view) {

    private val model = NovelDetailsModel(mContext)
    var id:Int = intent.getIntExtra(Constant.ID,0)
    private var authorId = 0
    var hasAttention = false  //是否关注了该作者
    var novelBean = NovelDetailBean()


    fun getStoryDetails() {
        model.getNovelDetail(id,object : BaseSubscriber<NovelDetailBean>(){
            override fun onNext(t: NovelDetailBean?) {
                super.onNext(t)
                if (t != null) {
                    mView.fillNovelDetail(t)
                    novelBean = t
                    authorId = if (t.user.userId.isNullOrEmpty()) 0 else t.user.userId.toInt()
                    hasAttention = if (t.user.following.isNullOrEmpty()) false else  t.user.following.toInt() != 0
                    getCommentList(true)
                }else{
                    mView.showErrorView("数据异常")
                    Toast.makeText(mContext,"数据异常",Toast.LENGTH_LONG).show()
                }
            }

        })
    }


    fun sendComment(content:String) {
        if (!AccountService.hasBindMobile()) {
            try {
                if (mContext is DiaobaoBaseActivity){
                    SoftKeyboardUtil.hideSoftKeyboard(mContext)
                    (mContext as DiaobaoBaseActivity).presentWeexView("vue/personalcenter/TFBindMobileAlert.js?present=1")
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return
        }
        val url = "http://api.doufu.la/new_comment/novel_comment/send_comment"
        val params = mutableMapOf<String,Any>()
        params["content"] = content
        params["topic_id"] = novelBean.id
        TFHttpUtil.requestPost(url,params){json, error ->
            try {
                val data = json.getJSONObject("data")
                val res = data.getBoolean("res")
                mView.sendComment(res)
            } catch (e: Exception) {
                e.printStackTrace()
                mView.sendComment(false)
            }
        }
    }


    fun attentionUser() {
        if (hasAttention) {
            model.cancelAttentionUser(authorId,object : BaseSubscriber<Boolean>(){

                override fun onNext(t: Boolean?) {
                    super.onNext(t)
                    if (t!=null && t) {
                        hasAttention = false
                        mView.attentionUser(true, success = true)
                    }else{
                        mView.attentionUser(true, success = false)
                    }
                }

                override fun onError(e: Throwable?) {
                    super.onError(e)
                    mView.attentionUser(true, success = false)
                }

            })
        }else{
            model.attentionUser(authorId,object : BaseSubscriber<NovelAttentionBean>(){
                override fun onNext(t: NovelAttentionBean?) {
                    super.onNext(t)
                    if (t != null) {
                        hasAttention = true
                        mView.attentionUser(false, success = true)
                    }else{
                        mView.attentionUser(false, success = false)
                    }
                }

                override fun onError(e: Throwable?) {
                    super.onError(e)
                    mView.attentionUser(false, success = false)
                }
            })
        }
    }


    var last = 0

    fun getCommentList(isRefresh:Boolean) {
        if (isRefresh){
            last = 0
        }
        val url = "http://api.doufu.la/new_comment/novel_comment/novel"
        val params = mutableMapOf<String,Any>()
        params["id"] = novelBean.id
        params["last"] = last
        TFHttpUtil.requestGet(url,params){json, error ->
            try {
                val data = json.getJSONObject("data")
                val list = GsonUtil.jsonToList(data.getJSONArray("lastest_list").toJSONString(), Array<NovelCommentBean>::class.java)
                last = data.getIntValue("last")
                mView.getCommentList(isRefresh,list)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

    }

    fun praiseComment(id:Int,position:Int,cancel:Boolean/*是否取消赞*/){
        if (cancel) {
            model.cancelPraiseComment(id,object : BaseSubscriber<Boolean>(){
                override fun onNext(t: Boolean?) {
                    super.onNext(t)
                    if (t != null && t) {
                        mView.praiseComment(position,cancel,success = true)
                    }else{
                        mView.praiseComment(position,cancel,success = false)
                    }
                }

                override fun onError(e: Throwable?) {
                    super.onError(e)
                    mView.praiseComment(position,cancel,success = true)
                }
            })
        }else{
            model.praiseComment(id,object :BaseSubscriber<Boolean>(){
                override fun onNext(t: Boolean?) {
                    super.onNext(t)
                    if (t != null && t) {
                        mView.praiseComment(position,cancel,success = true)
                    }else{
                        mView.praiseComment(position,cancel,success = false)
                    }
                }

                override fun onError(e: Throwable?) {
                    super.onError(e)
                    mView.praiseComment(position,cancel,success = true)
                }

            })
        }
    }



    fun getShareBean(): ShareBeansInfo {
        val shareBean = ShareBeansInfo()
        shareBean.id = "$id"
        shareBean.dataType = 1
        var shareText = StringUtil.filterAllSpace(novelBean.description)
        if (shareText != null && shareText.length > 50) {
            shareBean.shartText = shareText.substring(0,50)
        }else{
            shareBean.shartText = shareText
        }
        shareBean.imagUrl = ""
        shareBean.title = "${novelBean.title}"
        shareBean.shareUrl = novelBean.shareUrl
        shareBean.object_type = "${novelBean.object_type}"
        return shareBean
    }

}